<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div>
      <img src="./one.png" alt="" srcset="" />
      <canvas id="myCanvas1"></canvas>
      <span>图片裁切</span>
    </div>
    <div>
      <div>图片压缩</div>
      <input type="file" id="upload" />
    </div>
    <div>
      <div>图片马赛克</div>
      <canvas id="text" width="200" height="200"></canvas>
    </div>
    <script>
      //图片裁切
      var canvas1 = document.getElementById('myCanvas1');
      var context1 = canvas1.getContext('2d');
      var img1 = new Image();
      img1.src = 'one.png';
      img1.onload = function () {
        context1.drawImage(img1, 60, 60, 60, 60, 60, 60, 60, 60);
      };

      //图片压缩
      const ACCEPT = ['image/jpg', 'image/png', 'image/jpeg'];
      const MAXSIZE_STR = 10;
      const MAXSIZE = MAXSIZE_STR * 1024 * 1024;
      convertImageToBase64 = (file, callback) => {
        let reader = new FileReader();
        reader.addEventListener('load', e => {
          const base64Image = e.target.result;
          callback && callback(base64Image);
          reader = null;
        });
        reader.readAsDataURL(file);
      };

      compress = (base64Image, callback) => {
        let maxW = 800;
        let maxH = 800;

        const image = new Image();
        image.addEventListener('load', e => {
          let ratio;
          let needCompress = false;
          if (maxW < image.naturalWidth) {
            needCompress = true;
            ratio = image.naturalWidth / maxW;
            maxH = image.naturalHeight / ratio;
          }
          if (maxH < image.naturalHeight) {
            needCompress = true;
            ratio = image.naturalHeight / maxH;
            maxW = image.naturalWidth / ratio;
          }
          if (!needCompress) {
            maxW = image.naturalWidth;
            maxH = image.naturalHeight;
          }
          // 创建画布
          const canvas = document.createElement('canvas');
          canvas.setAttribute('id', '__compress__');
          canvas.width = maxW;
          canvas.height = maxH;
          canvas.style.visibility = 'visible';
          document.body.appendChild(canvas);

          const ctx = canvas.getContext('2d');
          ctx.clearRect(0, 0, maxW, maxH);
          ctx.drawImage(image, 0, 0, maxW, maxH);
          const compressImage = canvas.toDataURL('image/png', 0.8);
          // console.log(compressImage);
          callback && callback(compressImage);
          canvas.remove();
          const _image = new Image();
          _image.src = compressImage;
          document.body.appendChild(_image);
          console.log('压缩比', +image.src.length / _image.src.length);
        });
        console.log(base64Image);
        image.src = base64Image;
        document.body.appendChild(image);
      };

      //上传函数
      uploadToServer = compressImage => {
        alert('上传到服务器');
        console.table('upload to server', compressImage);
      };

      const upload = document.getElementById('upload');

      upload.addEventListener('change', function (e) {
        console.log(e.target.files);
        const [file] = e.target.files;
        if (!file) {
          return;
        }
        const { type: fileType, size: fileSize } = file;
        if (!ACCEPT.includes(fileType)) {
          alert(`不支持[${fileType}]类型`);
          upload.value = ''; //将对象重置
          return;
        }
        if (fileSize > MAXSIZE) {
          console.log(fileSize);
          alert(`文件超出${MAXSIZE_STR}Mb!`);
          upload.value = '';
          return;
        }
        convertImageToBase64(file, base64Image =>
          compress(base64Image, uploadToServer)
        );
      });

      var canvas = document.querySelector('#text');
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d');
        var img = new Image();
        img.src = 'one.png';
        img.onload = function () {
          canvas.width = img.width * 2;
          canvas.height = img.height;
          draw();
        };
        function draw() {
          ctx.drawImage(img, 0, 0);
          var oldImgdata = ctx.getImageData(0, 0, img.width, img.height);
          var newImgdata = ctx.createImageData(img.width, img.height);

          var size = 7;
          for (var i = 0; i < oldImgdata.width / size; i++) {
            for (var j = 0; j < oldImgdata.height / size; j++) {
              var color = getPxinfo(
                oldImgdata,
                i * size + Math.floor(Math.random() * size),
                j * size + Math.floor(Math.random() * size)
              );
              for (var a = 0; a < size; a++) {
                for (var b = 0; b < size; b++) {
                  setPxinfo(newImgdata, i * size + a, j * size + b, color);
                }
              }
            }
          }
          ctx.putImageData(newImgdata, img.width, 0);
        }

        function getPxinfo(imgdata, x, y) {
          var color = [];
          var data = imgdata.data;
          var w = imgdata.width;
          var h = imgdata.height;
          color[0] = data[(y * w + x) * 4];
          color[1] = data[(y * w + x) * 4 + 1];
          color[2] = data[(y * w + x) * 4 + 2];
          color[3] = data[(y * w + x) * 4 + 3];
          return color;
        }

        function setPxinfo(imgdata, x, y, color) {
          var data = imgdata.data;
          var w = imgdata.width;
          var h = imgdata.height;
          data[(y * w + x) * 4] = color[0];
          data[(y * w + x) * 4 + 1] = color[1];
          data[(y * w + x) * 4 + 2] = color[2];
          data[(y * w + x) * 4 + 3] = color[3];
        }
      }
    </script>
  </body>
  <style></style>
</html>
